package ru.classbase.dbdumper.postgres

import org.springframework.stereotype.Component
import ru.classbase.dbdumper.AppProperties
import ru.classbase.dbdumper.Dumper
import ru.classbase.dbdumper.model.DatabaseProduct
import ru.classbase.dbdumper.model.DbMetaData
import java.sql.Connection
import javax.sql.DataSource


@Component
class PostgresDumper(
    private val dataSource: DataSource,
    private val props: AppProperties,
    private val metaInfoExtractor: PostgresMetaInfoExtractor,
) : Dumper {

    override val supportedDatabase = DatabaseProduct.POSTGRES

    override fun getMetaData() = metaInfoExtractor.getMetaData(props.schemas)

    override fun lockTables(meta: DbMetaData): Connection {
        val tables = meta.schemas.flatMap { entry -> entry.value.tables.map { "${entry.key}.${it.key}" } }.toSet()
            .joinToString(",")

        val sql = "lock table $tables in access share mode"

        val conn = dataSource.connection
        conn.autoCommit = false

        conn.createStatement().use { stmt ->
            stmt.queryTimeout = props.lockTimeout
            stmt.execute(sql)
        }

        return conn
    }

}